package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.home.api.SupervisionItemManagementFeign;
import com.eastfair.home.dto.SupervisionItemManagementDTO;
import com.eastfair.venueservice.dao.ExhibitionServiceProviderMapper;
import com.eastfair.venueservice.dto.ExhibitionServiceProviderDTO;
import com.eastfair.venueservice.dto.ExhibitionServiceProviderQuery;
import com.eastfair.venueservice.dto.ServiceProviderSpaceDTO;
import com.eastfair.venueservice.entity.ExhibitionServiceProvider;
import com.eastfair.venueservice.entity.ServiceProvider;
import com.eastfair.venueservice.entity.ServiceProviderSpace;
import com.eastfair.venueservice.enumeration.ServiceProviderTypeEnum;
import com.eastfair.venueservice.service.ExhibitionServiceProviderService;
import com.eastfair.venueservice.service.ServiceProviderService;
import com.eastfair.venueservice.service.ServiceProviderSpaceService;
import com.eastfair.venueservice.vo.ExhibitionServiceProviderVO;
import com.eastfair.venueservice.vo.ServiceProviderSpaceVO;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 展会服务商关系
 * </p>
 *
 * @author linan
 * @date 2022-07-15
 */
@Slf4j
@Service
public class ExhibitionServiceProviderServiceImpl extends SuperServiceImpl<ExhibitionServiceProviderMapper, ExhibitionServiceProvider> implements ExhibitionServiceProviderService {

    @Resource
    private ServiceProviderService serviceProviderService;
    @Resource
    private ServiceProviderSpaceService serviceProviderSpaceService;
    @Resource
    private SupervisionItemManagementFeign supervisionItemManagementFeign;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ExhibitionServiceProvider> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    @Override
    protected R<Boolean> handlerSave(ExhibitionServiceProvider model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public List<ServiceProviderVO> queryExhibitionServiceProvider(ExhibitionServiceProviderQuery query) {
        Long exhibitionManageId = query.getExhibitionManageId();
        List<String> spaceNos =CollectionUtils.isEmpty(query.getServiceProviderSpaces()) ? new ArrayList<>() :  query.getServiceProviderSpaces().stream().map(ServiceProviderSpaceDTO::getSpaceCode).collect(Collectors.toList());
        // 先查询展会下的服务商
        List<ExhibitionServiceProvider> list = list(new QueryWrapper<ExhibitionServiceProvider>()
                .lambda()
                .eq(ExhibitionServiceProvider::getIsDeleted, BusinessConstant.NO)
                .eq(exhibitionManageId != null, ExhibitionServiceProvider::getExhibitionManageId, exhibitionManageId)
                .eq(query.getServiceProviderId() != null, ExhibitionServiceProvider::getServiceProviderId, query.getServiceProviderId())
                .like(StringUtils.isNotBlank(query.getServiceProviderName()),ExhibitionServiceProvider::getServiceProviderName, query.getServiceProviderName())
                .eq(StringUtils.isNotBlank(query.getServiceProviderType()), ExhibitionServiceProvider::getServiceProviderType, query.getServiceProviderType()));
        List<ServiceProviderVO> serviceProviderVOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for (ExhibitionServiceProvider exhibitionServiceProvider : list) {
                List<ServiceProviderSpace> serviceProviderSpaceList = serviceProviderSpaceService.list(new QueryWrapper<ServiceProviderSpace>().lambda()
                        .eq(ServiceProviderSpace::getIsDeleted, BusinessConstant.NO)
                        .in(CollectionUtils.isNotEmpty(spaceNos), ServiceProviderSpace::getSpaceCode,spaceNos)
                        .eq(ServiceProviderSpace::getExhibitionServiceProviderId, exhibitionServiceProvider.getId()));
                // 查询
                ServiceProvider serviceProvider = serviceProviderService.getById(exhibitionServiceProvider.getServiceProviderId());
                if(Objects.nonNull(serviceProvider)){
                    ServiceProviderVO serviceProviderVO = BeanUtil.copyProperties(serviceProvider, ServiceProviderVO.class);
                    List<ServiceProviderSpaceVO> serviceProviderSpaceVOS = ConvertUtil.convertList(serviceProviderSpaceList, ServiceProviderSpaceVO.class);
                    serviceProviderVO.setServiceProviderSpaces(serviceProviderSpaceVOS);
                    serviceProviderVOS.add(serviceProviderVO);
                }
            }
        }
        return serviceProviderVOS;
    }

    @Override
    public List<ExhibitionServiceProvider> listExhibitionServiceProvider(ExhibitionServiceProviderDTO query) {
        log.info("listExhibitionServiceProvider - 查询展会服务商关系, query={}", query);
        QueryWrapper<ExhibitionServiceProvider> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ExhibitionServiceProvider::getIsDeleted, BusinessConstant.NO)
                .eq(query.getExhibitionManageId() != null, ExhibitionServiceProvider::getExhibitionManageId, query.getExhibitionManageId())
                .eq(query.getServiceProviderId() != null, ExhibitionServiceProvider::getServiceProviderId, query.getServiceProviderId())
                .eq(StrUtil.isNotBlank(query.getServiceProviderType()), ExhibitionServiceProvider::getServiceProviderType, query.getServiceProviderType())
        ;
        return list(queryWrapper);
    }

    @Override
    public List<ExhibitionServiceProvider> listByExhibitionManageId(Long exhibitionManageId) {
        log.info("listByExhibitionManageId - 展会ID查询展会服务商关系, exhibitionManageId={}", exhibitionManageId);
        ExhibitionServiceProviderDTO query = new ExhibitionServiceProviderDTO();
        query.setExhibitionManageId(exhibitionManageId);
        return listExhibitionServiceProvider(query);
    }

    @Override
    public List<ServiceProviderVO> listVOByExhibitionManageId(Long exhibitionManageId, Long serviceProviderId) {
        ExhibitionServiceProviderQuery query = new ExhibitionServiceProviderQuery();
        query.setExhibitionManageId(exhibitionManageId);
        query.setServiceProviderId(serviceProviderId);
        return queryExhibitionServiceProvider(query);
    }

    @Override
    public List<ServiceProviderVO> listServiceProvidersByExhibitionId(Long exhibitionId, List<String> spaceCodeList, String serviceProviderType) {
        ExhibitionServiceProviderQuery query = new ExhibitionServiceProviderQuery();
        query.setExhibitionManageId(exhibitionId);
        query.setServiceProviderType(serviceProviderType);
        List<ServiceProviderSpaceDTO> serviceProviderSpaceDTOList = spaceCodeList
                .stream()
                .map(spaceCode -> {
                    ServiceProviderSpaceDTO serviceProviderSpaceDTO = new ServiceProviderSpaceDTO();
                    serviceProviderSpaceDTO.setSpaceCode(spaceCode);
                    return serviceProviderSpaceDTO;
                })
                .collect(Collectors.toList());
        query.setServiceProviderSpaces(serviceProviderSpaceDTOList);
        return queryExhibitionServiceProvider(query);
    }

    @Override
    public Map<String, List<ServiceProviderVO>> getServiceProviderVOMapByExhibitionId(Long exhibitionId, List<String> spaceCode, String serviceProviderType) {
        List<ServiceProviderVO> homeList = listServiceProvidersByExhibitionId(exhibitionId, spaceCode, serviceProviderType);
        if (homeList == null || homeList.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<String, List<ServiceProviderVO>> serviceProviderMap = new HashMap<>(16);
        for (ServiceProviderVO serviceProviderVO : homeList) {
            List<ServiceProviderSpaceVO> serviceProviderSpaces = serviceProviderVO.getServiceProviderSpaces();
            if (serviceProviderSpaces == null || serviceProviderSpaces.isEmpty()) {
                continue;
            }
            for (ServiceProviderSpaceVO serviceProviderSpaceVO : serviceProviderSpaces) {
                List<ServiceProviderVO> serviceProviderList = serviceProviderMap.get(serviceProviderSpaceVO.getSpaceCode());
                if (serviceProviderList == null || serviceProviderList.isEmpty()) {
                    serviceProviderList = new ArrayList<>();
                    serviceProviderMap.put(serviceProviderSpaceVO.getSpaceCode(), serviceProviderList);
                }
                serviceProviderList.add(serviceProviderVO);
            }
        }
        return serviceProviderMap;
    }

    @Override
    public ServiceProviderVO getHomeByExhibitionIdAndSpaceCode(Long exhibitionId, String spaceCode) {
        log.info("getHomeByExhibitionAndSpaceCode - 展会ID和展厅编码查询负责的主场, exhibitionId={}, spaceCode={}", exhibitionId, spaceCode);
        List<String> spaceCodeList = new ArrayList<>();
        spaceCodeList.add(spaceCode);
        Map<String, List<ServiceProviderVO>> serviceProviderMap = getServiceProviderVOMapByExhibitionId(exhibitionId, spaceCodeList, ServiceProviderTypeEnum.HOME_SERVICE_PROVIDER.getCode());
        List<ServiceProviderVO> homeList = serviceProviderMap.get(spaceCode);
        if (homeList == null || homeList.isEmpty()) {
            return null;
        }
        return homeList.get(0);
    }

    @Override
    public ServiceProviderVO getHomeByExhibitionId(Long exhibitionId) {
        ExhibitionServiceProviderQuery query = new ExhibitionServiceProviderQuery();
        query.setExhibitionManageId(exhibitionId);
        query.setServiceProviderType(ServiceProviderTypeEnum.HOME_SERVICE_PROVIDER.getCode());
        List<ServiceProviderVO> serviceProviderList = queryExhibitionServiceProvider(query);
        if (serviceProviderList == null || serviceProviderList.isEmpty()) {
            return null;
        }
        return serviceProviderList.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveExhibitionServiceProvider(ExhibitionServiceProviderDTO exhibitionServiceProviderDTO) {
        // 检查是否已经保存过展会服务商关系
        ExhibitionServiceProviderDTO query = new ExhibitionServiceProviderDTO();
        query.setExhibitionManageId(exhibitionServiceProviderDTO.getExhibitionManageId());
        query.setServiceProviderId(exhibitionServiceProviderDTO.getServiceProviderId());
        List<ExhibitionServiceProvider> existExhibitionServiceProviderList = listExhibitionServiceProvider(query);
        if (existExhibitionServiceProviderList != null && !existExhibitionServiceProviderList.isEmpty()) {
            return true;
        }
        // 保存展会服务商关系
        ExhibitionServiceProvider exhibitionServiceProvider = BeanUtil.copyProperties(exhibitionServiceProviderDTO, ExhibitionServiceProvider.class, "id");
        Long serviceProviderId = exhibitionServiceProvider.getServiceProviderId();
        ServiceProvider serviceProvider = serviceProviderService.getById(serviceProviderId);
        if(Objects.nonNull(serviceProvider)){
            exhibitionServiceProvider.setServiceProviderName(serviceProvider.getCompanyName());
        }
        save(exhibitionServiceProvider);
        // 批量保存服务商展厅关系
        List<ServiceProviderSpaceDTO> serviceProviderSpaceDTOList = exhibitionServiceProviderDTO.getServiceProviderSpaceList();
        if (serviceProviderSpaceDTOList == null || serviceProviderSpaceDTOList.isEmpty()) {
            return true;
        }
        return serviceProviderSpaceService.saveBatch(serviceProviderSpaceDTOList, exhibitionServiceProvider.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<ExhibitionServiceProviderDTO> exhibitionServiceProviderDTOList, Long exhibitionManageId) {
        if (exhibitionServiceProviderDTOList == null || exhibitionServiceProviderDTOList.isEmpty()) {
            return false;
        }
        for (ExhibitionServiceProviderDTO exhibitionServiceProviderDTO : exhibitionServiceProviderDTOList) {
            ServiceProvider provider = serviceProviderService.getById(exhibitionServiceProviderDTO.getServiceProviderId());
            // 保存展会服务商关系
            exhibitionServiceProviderDTO.setExhibitionManageId(exhibitionManageId);
            saveExhibitionServiceProvider(exhibitionServiceProviderDTO);
            // 初始化监督项管理
            if(exhibitionServiceProviderDTO.getServiceProviderType().equals(ServiceProviderTypeEnum.HOME_SERVICE_PROVIDER.getCode())){
                supervisionItemManagementFeign.saveSupervisionItemManagement(SupervisionItemManagementDTO.builder()
                        .homeCourtId(exhibitionServiceProviderDTO.getServiceProviderId())
                        .homeCourtName(Objects.nonNull(provider) ? provider.getCompanyName() : null)
                        .exhibitionManageId(exhibitionServiceProviderDTO.getExhibitionManageId()).build());
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByByExhibitionManageId(Long exhibitionManageId) {
        log.info("removeByByExhibitionManageId - 展会ID删除展会服务商关系, exhibitionManageId={}", exhibitionManageId);
        // 查询现在的展会服务商绑定关系
        List<ExhibitionServiceProvider> list = listByExhibitionManageId(exhibitionManageId);
        if (list == null || list.isEmpty()) {
            return false;
        }
        // 删除现在的展会服务商绑定关系
        return removeByIdsOfLogic(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByServiceProvider(ExhibitionServiceProviderDTO exhibitionServiceProviderDTO) {
        log.info("removeByServiceProvider - 移除展会下的服务商关系, exhibitionServiceProviderDTO={}", exhibitionServiceProviderDTO);
        List<ExhibitionServiceProvider> list = listExhibitionServiceProvider(exhibitionServiceProviderDTO);
        if (list == null || list.isEmpty()) {
            return false;
        }
        List<Long> ids = list
                .stream()
                .map(SuperEntity::getId)
                .collect(Collectors.toList());
        return removeByIds(ids);
    }
}
